
import { getToken, setToken} from '@/utils/auth.js'
import { ref, onMounted } from 'vue'
import { onShow, onHide, onLoad } from "@dcloudio/uni-app"
import { common } from "@/utils/api.js"
import cache from '@/utils/cached.js'

export const loginInit = () => {

  const routeParams = ref({})
  const provider = ref('')

  onLoad((options) => {
    // if (uni.getSystemInfoSync().browserName == 'safari' || uni.getSystemInfoSync().browserName == 'chrome') {
    //   setToken('Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJHcmFjZS5HbG91ZE1hbGwiLCJpc3MiOiJHcmFjZS5HbG91ZE1hbGwiLCJuYW1laWQiOiIzYTE4YzExYy1hOTliLTU0NjItM2RmMC1iMGFmZDMwY2QwZTkiLCJ1bmlxdWVfbmFtZSI6Iue9l-Wjq-a0i-mYv-iKseS4qiIsImNsaWVudF9pZCI6Im9NMkJZN0dHUUM2N1MxNGtkMTJFUVg3Zlk4Z2siLCJuYmYiOjE3NDUzMjIzNDEsImV4cCI6MTc0NzkxNDM0MSwiaWF0IjoxNzQ1MzIyMzQxfQ.F4VgtBG_bHMT2uzRzE8WDXsBpC16wdNzhOQIFRar3rc')
    //   redirect()
    // } else {
    //   console.log('initPage params:', options)
    //   routeParams.value = options || {};
    //   if (getToken()) {
    //     redirect()
    //   } else {
    //     login()
    //   }
    // }

    // console.log('hooks initPage params:', options)
    // routeParams.value = options || {};
    // if (getToken()) {
    //   redirect()
    // } else {
    //   console.log('initPage params:', options)
    //   routeParams.value = options;
    //   if (getToken()) {
    //     redirect()
    //   } else {
    //     login()
    //   }
    // }

    console.log('hooks initPage params:', options)
    routeParams.value = options || {};
    if (getToken()) {
      redirect()
    } else {
      login()
    }
  })

  async function login() {
    let result = await weiLogin()
    if (!result.code) return;
    const { data } = await httpLogin(result.code, result.provider)
    const userInfo = {
      avatar: data.avatar,
      nickName: data.nick,
      phone: data.phone,
      userId: data.id
    }
    
    if (!data.isComplete) {
      const res2 = await getInfo(result.code)
      userInfo['avatar'] = res2.userInfo.avatarUrl;
      userInfo['nickName'] = res2.userInfo.nickName;
    }

    setUserInfo(userInfo)
    redirect()
  }
  function weiLogin() {
    return new Promise(resolve => {
      uni.getProvider({
        service: 'oauth',
        success: function (res) {
          console.log(res.provider)
          provider.value = res.provider[0];
          uni.login({
            provider: res.provider[0],
            success: (result) => {
              console.log(result);
              resolve({
                ...result,
                provider: res.provider[0]
              })
            },
            fail: (error) => {
              console.log(error);
            }
          })
        }
      });
      
    })
  }
  function httpLogin(code, type) {
    let parentId;
    if (routeParams.value.scene) {
      parentId = routeParams.value.scene
    } else if(routeParams.value.userId) {
      parentId = decodeURIComponent(routeParams.value.userId)
    } else {
      parentId = ''
    }
    
    let requestFunc;
    if (type === 'weixin') {
      requestFunc = common.login_wx
    } else if (type === 'kuaishou') {
      requestFunc = common.login_ks
    }

    return requestFunc({
      code: code,
      parentId: parentId
    })
    .then(res => {{
      if (res.code == 200)
        setToken(res.data.token)
      }
      return res
    })
  }
  function getInfo() {
    return new Promise(resolve => {
      uni.getUserInfo({
        provider: provider.value,
        success: (info) => {
          // 获取用户信息成功, info.authResult保存用户信息
          resolve(info)
        }
      })
    })
  }
  function setUserInfo(userInfo) {
    cache.setUserInfo(userInfo)
  }
  function redirect() {
    if (routeParams.value.from == 'goodsInfo') {
      // uni.navigateTo({ url: '/pages/index/index' })
      setTimeout(() => {
        let goodsId = decodeURIComponent(routeParams.value.id)
        uni.navigateTo({ url: '/pages/goods-info/goods-info?id=' + goodsId })
      }, 2000)
    } else {
      // uni.navigateTo({ url: '/pages/index/index' })
    }
  }

  return { login }
}